﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using Nb.Common;
using Nb.Common.Db;

namespace Nb.Tools.DbManager.Libs.Backups
{
    public class BackupService
    {
        public IList<BackupFile> ListAllBackupFiles(string theDirPath)
        {
            var backupFiles = MyIOHelper.GetFiles(theDirPath, "*.bak", SearchOption.TopDirectoryOnly)
                .Select(x => new FileInfo(x))
                .Select(file => new BackupFile() { FileName = file.Name, FilePath = file.FullName, CreatedAt = file.CreationTime })
                .OrderByDescending(x => x.CreatedAt)
                .ToList();

            return backupFiles;
        }

        public MessageResult BackupDb(string connName, string databaseName, string bakFilePath)
        {
            var backupDb = MyDbHelper.Call(connName).BackupDb(databaseName, bakFilePath);
            string message = string.Format("数据库到文件{0}备份{1}", bakFilePath, backupDb ? "成功" : "失败");
            return new MessageResult(backupDb, message);
        }

        public MessageResult RestoreDb(string connName, string databaseName, string bakFilePath)
        {
            //if (string.IsNullOrWhiteSpace(bakFilePath))
            //{
            //    var backupDirPath = _myFileHelper.MakeAppDataPathForApp("Backups");

            //    var theLastCreatedFile = MyIOHelper.GetFiles(backupDirPath, "*.bak", SearchOption.TopDirectoryOnly)
            //        .ToList()
            //        .Select(x => new FileInfo(x))
            //        .OrderByDescending(file => file.CreationTime)
            //        .FirstOrDefault();

            //    if (theLastCreatedFile == null)
            //    {
            //        //没有找到任何备份文件
            //        return new MessageResult(false, string.Format("路径下没有找到任何备份文件: {0}", backupDirPath));
            //    }
            //    bakFilePath = theLastCreatedFile.FullName;
            //}

            var restoreDb = MyDbHelper.Call(connName).RestoreDb(databaseName, bakFilePath);
            string message = string.Format("数据库从文件{0}还原{1}", bakFilePath, restoreDb ? "成功" : "失败");
            return new MessageResult(restoreDb, message);
        }
    }
}